package com.share.tool.generator.db_tranfer_file;

import com.share.common.utils.*;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;

/**
 * @author 01401061 - 孙艳强
 * @date 2020/10/29 21:58
 */

public class MainDbFile {
    public static void help() {
        System.out.println("用法:");
        System.out.println("\t w /a/a.txt  #写文件到数据库");
        System.out.println("\t r 10  #读取id=10文件");
        System.out.println("\t s  #查看文件列表");
        System.out.println("\t h  #帮助");
        System.out.println("\t q  #退出");
    }

    public static void main(String[] args) throws Exception {
        //初始化数据库
        Properties properties = null;
        try {
            properties = FileUtil.readPropertiesFromHome("application.properties");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (properties == null) {
            properties = FileUtil.readPropertiesFromCp("application.properties");
        }

        String driver = properties.getProperty("spring.datasource.driver-class-name");
        String url = properties.getProperty("spring.datasource.url");
        String user = properties.getProperty("spring.datasource.username");
        String passwd = properties.getProperty("spring.datasource.password");
        String OPTION = "?serverTimezone=UTC";
        Connection con = DbUtil.getConnection(driver, url + OPTION, user, passwd);
        help();

        //初始化输出
        Scanner scanner = new Scanner(System.in); // 创建Scanner对象
        while (true) {
            String str = scanner.nextLine(); // 读取一行输入并获取字符串
            if (StringUtils.isBlank(str)) {
                continue;
            }

            String line[] = strSpit(str);
            String opt = line[0];
            if ("q,exit,e".contains(opt)) {
                break;
            }

            switch (opt) {
                case "h":
                    help();
                    break;
                case "s":
                    showInfo(con);
                    break;
                case "w":
                    writeFile2db(con, line[1]);
                    break;
                case "r":
                    readDb2File(con, new Integer(line[1]));
                    break;
                case "init":
                    createTable(con);
                    break;
                default:
                    System.out.println("输入错误请重试");
                    break;
            }
        }
    }

    private static boolean createTable(Connection con) {
        Boolean res = false;
        try {
            String sql = FileUtil.readFromCp("init.sql");
            PreparedStatement ps = con.prepareStatement(sql);
            res = ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("数据库建表");
        return res;
    }

    private static String[] strSpit(String path) {
        List<String> arr = new LinkedList<>();
        String[] s = path.split(" ");
        for (String tmp : s) {
            String a = tmp.trim();
            if (a.length() <= 0) {
                break;
            } else {
                arr.add(a);
            }
        }
        return arr.toArray(new String[10]);
    }

    private static int writeFile2db(Connection con, String path) throws Exception {
        File file = new File(path);
        String filename = file.getName();

        byte[] bytes = FileUtil.readByte(path);
        String base64Value = Base64Util.encodeToString(bytes);

        String md5 = Md5Util.encodeByMD5(base64Value);
        String create_time = DateUtil.getDateTime();
        int len = base64Value.length();

        String sql = "INSERT INTO tt_tmp(`content`, `name`, `len`,`md5`, `create_time`) VALUES ('" + base64Value + "', '" + filename + "', '" + len + "','" + md5 + "', '" + create_time + "')";
        PreparedStatement ps = con.prepareStatement(sql);
        int res = ps.executeUpdate();

        System.out.println("文件保存至数据库=" + (res > 0 ? "成功" : "失败"));
        return res;
    }

    private static int readDb2File(Connection con, int id) throws Exception {
        PreparedStatement ps = con.prepareStatement("select content,name from tt_tmp where id =" + id);
        ResultSet rs = ps.executeQuery();
        List<Map<String, Object>> mapList = DbUtil.convertToList(rs);
        if (mapList == null || mapList.isEmpty()) {
            System.out.println("编号不存在!");
            return 0;
        } else {
            Object content = mapList.get(0).get("content");
            Object name = mapList.get(0).get("name");
            File filename = null;
            if (name != null && StringUtils.isNotBlank(name.toString())) {
                filename = new File(name.toString());
            } else {
                return -1;
            }
            System.out.println("从数据库读数据保存的文件路径=" + filename.getAbsolutePath());
            String base64Value = (content == null) ? null : content.toString().trim();
            byte[] value = Base64Util.decode(base64Value.getBytes());
            return FileUtil.writeByte(filename, value) ? 1 : 0;
        }
    }

    private static int showInfo(Connection con) throws Exception {
        //id	name	len
        PreparedStatement ps = con.prepareStatement("select id,name,len,md5 from tt_tmp");
        ResultSet rs = ps.executeQuery();
        List<Map<String, Object>> mapList = DbUtil.convertToList(rs);
        System.out.println("id\tname\tlen\tmd5");
        for (Map<String, Object> tmpMap : mapList) {
            String line = "";
            for (String key : tmpMap.keySet()) {
                Object tmpValue = tmpMap.get(key);
                String value = (tmpValue == null) ? "-" : tmpValue.toString().trim();
                line += value + "\t";
            }
            System.out.println(line);
        }
        return mapList.size();
    }
}
